<?php

class SystemAccountController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return $this->getRules();
	}

	public function actionIndex(){
            //init page value
            $pagevals = array(
                'page_title' => "Quản trị tài khoản hệ thống",
                'subpage_title' => 'Danh sách tài khoản hệ thống',
                //'action' => 'systemAccount/abc'
            );
            
            $paging_limit_number = SystemConfigModel::model()->findByPk('1')->paging_limit_number;
            $page_number = isset($_GET['page_number']) ? intval($_GET['page_number']) : 1;
            $status = isset($_GET['status']) ? $_GET['status'] : 'all';
            $condition = array();
            $sort = array();

            $data = SystemAccountModel::model()->getByPage($condition, $page_number, $paging_limit_number, $sort);
            $pagevals['total_row'] = SystemAccountModel::model()->countRow($condition);

            $pagevals['page_number'] = $page_number;
            $pagevals['total_page'] = SystemAccountModel::model()->countPage($pagevals['total_row'], $paging_limit_number);
            $pagevals['row_start'] = SystemAccountModel::model()->get_start_row($pagevals['total_row'], $page_number, $paging_limit_number);
            $pagevals['row_end'] = SystemAccountModel::model()->get_end_row($pagevals['total_row'], $page_number, $paging_limit_number);
             $pagevals['status'] = $status;
             
            $this->display("systemAccount/index", array('data'=>$data, 'pagevals'=>$pagevals) );
        }
        
        public function actionCreate()
	{
            $pagevals = array(
                    'page_title' => "Quản trị tài khoản hệ thống",
                    'subpage_title' => 'Tạo tài khoản hệ thống mới',
                );
            
            if(isset($_POST['username']) && !isset($_POST['email']) ){
                
                $user = SystemAccountModel::model()->findByAttributes(array('username'=>$_POST['username']));
 
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
                
            }
            
            else if(isset($_POST['email']) && !isset($_POST['username'])){
                $user = SystemAccountModel::model()->findByAttributes(array('email'=>$_POST['email']));
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
            }

            
            else if(isset($_POST['username']) && isset($_POST['email'])){
                
                $systemAccount = new SystemAccountModel;
                
                if($this->checkinput('username') == false){
                    die ('Username duplicated');
                }
                
                if($this->checkinput('email') == false){
                    die ('Email duplicated');
                }
   
  
                $systemAccount->attributes = array(
                                        //'id' => $_POST[''],
                                        'username' => $_POST['username'],
                                        'password' => md5($_POST['password']),
                                        'email' => $_POST['email'],
                                        'phone' => $_POST['phone'],
                                        'status' => 'active',
                                    );
                if($systemAccount->save(false)){
                        $this->redirect(array('index'));
                }
            }
                
            else {
                $this->display("systemAccount/create", array('pagevals'=>$pagevals)); 
            }
	}
        

        public function actionEdit($id)
	{
            if(!isset($_GET['id'])){
                die('System account not found');
            }
                
            $pagevals = array(
                'page_title' => "Quản trị tài khoản hệ thống",
                'subpage_title' => 'Chỉnh sửa tài khoản hệ thống',
                //'action' => 'systemAccount/abc'
            );
            //-------------------------------
            //get systemAccount data
            $systemAccount = SystemAccountModel::model()->findByPk($id);
            if(!is_object($systemAccount)){
                die('System account not found');
            }

            if(isset($_POST['email'])){
                if(isset($_POST['password'])){
                    $systemAccount->attributes = array(
                                        //'id' => $_POST[''],
                                        //'username' => $_POST['username'],
                                        'password' => md5($_POST['password']),
                                        'email' => $_POST['email'],
                                        'phone' => $_POST['phone'],
                                        //'status' => 'active',
                                    );
                }else{
                    $systemAccount->attributes = array(
                                        //'id' => $_POST[''],
                                        //'username' => $_POST['username'],
                                        //'password' => $_POST['password'],
                                        'email' => $_POST['email'],
                                        'phone' => $_POST['phone'],
                                        //'status' => 'active',
                                    );
                }
                
                if($systemAccount->save(false)){
                        $this->redirect(array('index'));
                }
            }
            $this->display("systemAccount/edit", array('pagevals'=>$pagevals,'data'=>$systemAccount->attributes));
        }
        
        public function checkinput(){
            if(isset($_POST['username'])){
                $user = SystemAccountModel::model()->findByAttributes(array('username'=>$_POST['username']));
                if(is_object($user)){echo 'false'; return false;}
                else {echo 'true'; return true;}
            }
            
            if(isset($_POST['email'])){
                $user = SystemAccountModel::model()->findByAttributes(array('email'=>$_POST['email']));
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
            }
        }
        
        public function actionRemove(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->findByPk($_POST['id']);
                if($result->delete()) {
                    $system_permision = SystemAccountPermisionModel::model()->findAllByAttributes(array('username'=>$result->username));
                    if(count($system_permision)!=0){
                        foreach ($system_permision as $value){
                            $value->delete();
                        }
                    }
                }
                echo "success";
            }
            else die('Not enough params');
        }
        

        public function doAcion($status,$data){
            $i = 0;
            $time = time();
            $systemAccount_id = explode(';', $data);
            if(sizeof($systemAccount_id) == 0){
                echo 0;
            }
            else{
                foreach($systemAccount_id as $value){
                    if($value != 0){
                        $result = SystemAccountModel::model()->modify($value,array('status'=>$status));
                        if($result == true){
                            $i++;
                        }
                    }
                }
                echo $i;
            }
        }
        
        
        public function actionCopy(){
            if(isset($_POST['systemAccount_id'])){
                $i = 0;
                $systemAccount_id = explode(';', $_POST['systemAccount_id']);
                if(sizeof($systemAccount_id) == 0){
                    echo 0;
                }
                else{
                    foreach($systemAccount_id as $value){
                        if($value != 0){
                            $result = SystemAccountModel::model()->copy($value);
                            if($result == true){
                                $i++;
                            }
                        }
                    }
                    echo $i;
                }
            }
        }
        
        public function actionPending(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->modify($_POST['id'],array('status'=>'pending'));
                if($result == true) echo "success";
            }
            else die('Not enough params');
        }
        
        public function actionApproved(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->modify($_POST['id'],array('status'=>'approved'));
                if($result == true) echo "success";
            }
            else die('Not enough params');
        }
        
        public function actionActive(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->modify($_POST['id'],array('status'=>'active'));
                if($result == true) echo "success";
            }
            else die('Not enough params');
        }
        
        public function actionBlock(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->modify($_POST['id'],array('status'=>'blocked'));
                if($result == true) echo "success";
            }
            else die('Not enough params');
        }
        
        public function actionRestore(){
            if(isset($_POST['id'])){
                $result = SystemAccountModel::model()->modify($_POST['id'],array('status'=>'pending'));
                if($result == true) echo "success";
            }
            else die('Not enough params');
        }
        
        public function getFilterValue($fields){
            if(is_array($fields)){
                $result = array();
                foreach($fields as $key => $value){
                    $temp = SystemAccountModel::model()->getUnique($key, $value);
                    if(is_array($temp)){
                        foreach($temp as $val){
                            if($val[$key] !=null && $val[$key]!=''){
                                $result[$key][]= $val[$key];
                            }
                        }
                    }
                }
                return $result;
            }else return null;
        }

	/**
	 * Performs the AJAX validation.
	 * @param SystemAccountModel $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='system-account-model-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}